package handler

import (
	"car-sys/cache"
	"car-sys/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func OrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	/*
		SELECT
		  orders.id as OrderId,
		  big_cars.big_car_no AS BigCarNo,
		  big_cars.big_car_code AS BigCarCode,
		  big_cars.big_car_name AS BigCarName,
		  orders.order_code AS OrderCode,
		  orders.order_form AS OrderForm,
		  orders.order_to AS OrderTo
		FROM
		  orders
		  LEFT JOIN big_cars ON orders.bid = big_cars.id

	*/
	var orderList []models.OrderList
	redis_key := "order_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("orders").
			Select(
				"orders.id as OrderId",
				"big_cars.big_car_no AS BigCarNo",
				"big_cars.big_car_code AS BigCarCode",
				"big_cars.big_car_name AS BigCarName",
				"orders.order_code AS OrderCode",
				"orders.order_form AS OrderForm",
				"orders.order_to AS OrderTo",
			).
			Joins("LEFT JOIN big_cars ON orders.bid = big_cars.id").
			Offset(offset).Limit(size).Find(&orderList)
		jsonData, _ := json.Marshal(orderList)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &orderList)
	}
	var count int64
	models.DB.Model(&models.Car{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  orderList,
		"count": count,
	})
	return
}
func OrderDetail(c *gin.Context) {
	id := c.Query("id")
	/*
		SELECT
		  orders.id as OrderId,
		  big_cars.big_car_no AS BigCarNo,
		  big_cars.big_car_code AS BigCarCode,
		  big_cars.big_car_name AS BigCarName,
		  orders.order_code AS OrderCode,
		  orders.order_form AS OrderForm,
		  orders.order_to AS OrderTo
		FROM
		  orders
		  LEFT JOIN big_cars ON orders.bid = big_cars.id
		  WHERE orders.id =1
	*/
	var order models.OrderList
	redis_key := "order_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("orders").
			Select(
				"orders.id as OrderId",
				"big_cars.big_car_no AS BigCarNo",
				"big_cars.big_car_code AS BigCarCode",
				"big_cars.big_car_name AS BigCarName",
				"orders.order_code AS OrderCode",
				"orders.order_form AS OrderForm",
				"orders.order_to AS OrderTo",
			).
			Joins("LEFT JOIN big_cars ON orders.bid = big_cars.id").
			Where("orders.id = ?", id).Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": order,
	})
	return
}
